package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.frame.compiler.utils.KeyboardUtils;
import com.frame.compiler.utils.NetworkUtils;
import com.frame.compiler.widget.ToastUtil;
import com.frame.compiler.widget.loadingView.KProgressHUD;
import com.frame.compiler.widget.title.OnTitleBarListener;
import com.frame.compiler.widget.title.TitleBar;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.tools.ToastUtils;

import java.lang.reflect.Method;
import java.util.Random;

/**
 * ================================================
 * 作    者：彭俊鸿
 * 邮    箱：1031028399@qq.com
 * 版    本：1.0
 * 创建日期：2018/5/13
 * 描    述：activity基类
 * ================================================
 */
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {
    public final String TAG = this.getClass().getSimpleName();
    public KProgressHUD hud;//数据加载框空间
    protected TitleBar mTitleBar;
    protected ImmersionBar mImmersionBar;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //判断app状态
//        if (AppStatusManager.getInstance().getAppStatus() == AppStatusManager.STATUS_RECYCLE) {
//            // 非正常启动流程，直接重新初始化应用界面
//            BroadCastReceiveUtils.sendLocalBroadCast(this, BaseConstant.Action.SEND_RESET_APP);
//            return;
//        }

        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O || !isTranslucentOrFloating()) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设定为竖屏
        }
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);//禁用系统截屏
        if (FirstOnCreate()) {
            return;
        }
        if (isSetContentView()){
            if (getLayoutId()==-1){
                setContentView(getLayoutView());
            }else {
                setContentView(getLayoutId());
            }
        }

        afterSetcontentView();
        if (!NetworkUtils.isConnected()) {
            showShortToast("请开启网络!");
        }

        if (hasNeedTitle()) {
            initTitle();
        }
        initView();

        //初始化沉浸式
//        if (isImmersionBarEnabled()) {
            initImmersionBar();
//        }
        initData();
        initEvent();
    }

    //是否需要初始化布局
    protected boolean isSetContentView(){
        return true;
    }

    //在SetcontentView()之后做一些操作
    protected void afterSetcontentView() {}

    //判断是否是透明
    private boolean isTranslucentOrFloating() {
        boolean isTranslucentOrFloating = false;
        try {
            int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean) m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }

    //是否可以使用沉浸式
    protected boolean isImmersionBarEnabled() {
        return false;
    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this).statusBarDarkFont(true, 0.2f)
                .titleBarMarginTop(mTitleBar);
        mImmersionBar.init();
    }

    //是否需要标题 默认为true
    public boolean hasNeedTitle() {
        return true;
    }

    //初始化头部title
    public void initTitle() {
        mTitleBar = (TitleBar) findViewById(com.frame.compiler.R.id.title_bar);
        if (mTitleBar == null) {
            return;
        }
        mTitleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                leftTitleViewClick();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {
                rightTitleViewClick();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    //设置title的数据
    public void setTitle(String title) {
        if (mTitleBar != null) {
            mTitleBar.setTitle(title);
        }
    }

    //title左侧点击事件
    public void leftTitleViewClick() {
        onBackPressed();
        KeyboardUtils.hideSoftInput(mTitleBar);
    }

    //title右侧点击事件
    public void rightTitleViewClick() {
        showShortToast("title右侧点击事件");
    }

    //title右侧控件显示
    public void showRightView() {
        if (mTitleBar != null) {
            mTitleBar.getRightView().setVisibility(View.VISIBLE);
        } else {
            showShortToast("控件还未初始化!");
        }
    }

    //title右侧控件隐藏
    public void hideRightView() {
        if (mTitleBar != null) {
            mTitleBar.getRightView().setVisibility(View.GONE);
        } else {
            showShortToast("控件还未初始化!");
        }
    }

    //设置title右侧控件文字
    public void setRightTitleView(String text) {
        if (mTitleBar != null) {
            mTitleBar.setRightTitle(text);
        }
    }

    //设置title右侧控件文字
    public void setRightIcon(Drawable drawable) {
        if (mTitleBar != null) {
            mTitleBar.setRightIcon(drawable);
        }
    }

    //弹出提示框
    public void showShortToast(String tip) {
        if (isFinishing() || "Canceled".equals(tip)) {
            return;
        }
        ToastUtil.show(tip);
    }

    //显示数据加载框
    public void showWaitDialog() {
        showWaitDialog(null);
    }

    public KProgressHUD getHud() {
        return hud;
    }

    //显示数据加载框
    public void showWaitDialog(String tip) {
        if (isFinishing()) {
            return;
        }

        if (hud == null) {
            hud = KProgressHUD.create(BaseActivity.this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE);
        }

        if (!TextUtils.isEmpty(tip)) {
            hud.setLabel(tip);
        }
        hud.show();
    }

    //判断数据加载框是否显示
    public boolean isWaitShow() {
        return hud.isShowing();
    }

    //隐藏数据加载框
    public void hideWaitDialog() {
        if (hud != null && hud.isShowing()) {
            hud.dismiss();
            hud = null;
        }
    }

    @Override
    protected void onDestroy() {
        hideWaitDialog();
        setContentView(R.layout.layout_view_null);
        super.onDestroy();
    }

    //在界面初始化之前需要做的一些判断 可以重写改方法
    public boolean FirstOnCreate() {
        return false;
    }

    //获取布局的layout
    public abstract int getLayoutId();

    //获取布局的layout
    public View getLayoutView(){
        return null;
    }

    //初始化布局
    public void initView() {
    }

    //初始化数据
    public void initData() {
    }

    //初始化监听事件
    public void initEvent() {
    }

    @Override
    public void onClick(View v) {
    }

    //关闭页面
    public void goFinish() {
        onBackPressed();
        KeyboardUtils.hideSoftInput(this);
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    /**
     * startActivityForResult 方法优化
     */

    private OnActivityCallback mActivityCallback;
    private int mActivityRequestCode;

    public void startActivityForResult(Class<? extends Activity> clazz, OnActivityCallback callback) {
        startActivityForResult(new Intent(this, clazz), null, callback);
    }

    public void startActivityForResult(Intent intent, OnActivityCallback callback) {
        startActivityForResult(intent, null, callback);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        KeyboardUtils.hideSoftInput(this);
        // 查看源码得知 startActivity 最终也会调用 startActivityForResult
        super.startActivityForResult(intent, requestCode, options);
    }

    public void startActivityForResult(Intent intent, @Nullable Bundle options, OnActivityCallback callback) {
        // 回调还没有结束，所以不能再次调用此方法，这个方法只适合一对一回调，其他需求请使用原生的方法实现
        if (mActivityCallback == null) {
            mActivityCallback = callback;
            // 随机生成请求码，这个请求码必须在 2 的 16 次幂以内，也就是 0 - 65535
            mActivityRequestCode = new Random().nextInt((int) Math.pow(2, 16));
            startActivityForResult(intent, mActivityRequestCode, options);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (mActivityCallback != null && mActivityRequestCode == requestCode) {
            mActivityCallback.onActivityResult(resultCode, data);
            mActivityCallback = null;
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    public interface OnActivityCallback {

        /**
         * 结果回调
         *
         * @param resultCode 结果码
         * @param data       数据
         */
        void onActivityResult(int resultCode, @Nullable Intent data);
    }
}
